﻿using FCZLM.Core.Models;
using FCZLM.Core.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace FCZLM.Web.Controllers
{
    public class MessageController : Controller
    {
        private readonly IRepository<Messages, int> _messagesRepository;
        private readonly IRepository<Users, int> _userRepository;
        public MessageController(IRepository<Messages, int> messagesRepository, IRepository<Users, int> userRepository)
        {
            _messagesRepository = messagesRepository;
            _userRepository = userRepository;
           

        }
        public async Task<IActionResult> Index()
        {
            var username = HttpContext.Session.GetString("user");
            var user = _userRepository.FirstOrDefault(x => x.UserName == username);
            var list = _messagesRepository.GetAllList();
            ViewBag._messagesRepository = list;
            ViewBag.User=user;
            return View();
            
        }
        [HttpPost]
        public async Task<IActionResult> Index(Messages messages, string name1)
        {
            Users user1 = await _userRepository.FirstOrDefaultAsync(x => x.UserName == name1);
            messages.AskTime = DateTime.Now;
            messages.UserId = user1.Id;
            bool isSuccess = false;//后台是否添加成功，默认是失败
            string msg = "添加失败，请重试！";
            if (ModelState.IsValid)
            {
                isSuccess = true;
                msg = "添加成功，开始跳转！";
                await _messagesRepository.InsertAsync(messages);
            }
            return Json(new { isSuccess, msg });
        }
    }
}
